<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
date_default_timezone_set ( 'prc' );
class Order extends CI_Controller {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 保存订单信息,跳转到支付页面
	 */
	public function save() {
		$userid = $this->session->userdata ( 'id' );
		if(empty($userid)){
			return_json ( FALSE, '', '请重新登录后再操作！' );
		}
		$this->load->model ( 'user_model' );
		$user = $this->user_model->load($userid);
		
		$this->load->model ( 'config_model' );
		$config = $this->config_model->find_by_key ("state");
		if($config['value']==1){
			return_json ( FAlSE, '','当前时间无法下单！' );
		}
		//$orderdate= $this->common->getOrderDate($user['school']);
		$code = $this->uri->segment(3);
		$scode=$this->session->userdata('code');
		if($code==$scode){//防止重复提交表单
			return_json ( FALSE, '', '请勿重复提交！' );
		}
		$this->session->set_userdata ( 'code',$code);
		
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'shoppingcart_model' );
		$this->load->model ( 'product_model' );
		$shoppingcarts = $this->shoppingcart_model->find_by_user ( $userid );
		if(empty($shoppingcarts)){
			return_json ( FAlSE, '','购物车为空，无法下单！' );
		}
		$orderno = build_order_no ($userid);
		$total=$this->count_total_price($userid);
		$order = array (
			'orderno' => $orderno,
			'userid' => $userid,
			'order_time' => date ( "Y-m-d H:i:s" ),
			'total' => $total,
			'state' => 0
		);
		$this->db->trans_begin();
		$orderid=$this->order_model->create ( $order );
		if (!empty($orderid)) {//插入的新数据ID不为空
			foreach($shoppingcarts as $cart){
				$this->product_model->updateStock($user['school'],$cart['date'],$cart['productid'],$cart['type'],$cart['amount']);
				$temp2 = $this->product_model->find_by_school_date_product_type($user['school'],$cart['date'],$cart['productid'],$cart['type']);
				if(!empty($temp2)&$temp2['stock']<0){
					$this->db->trans_rollback();
					$str=date('m月d日',strtotime($cart['date']));
					return_json ( FAlSE, '',$str.'的'.$temp2['name'].'剩余数量不足！');
				}
				$orderdetail=array (
					'orderid' => $orderid,
					'productid' => $cart['productid'],
					'price' => $cart['price'],
					'amount' => $cart['amount'],
					'date' => $cart['date'],
					'type' => $cart['type']
			    );
				$this->orderdetail_model->create ( $orderdetail );
			}
			$this->shoppingcart_model->delete_by_user ( $userid );// 订单创建成功，清空购物车
			$product=$this->product_model->find_by_category ( 4 );//默认餐
			if(!empty($product)){
				$sdate = getSdate();//下周二
				$edate = getEdate();//下下周一
				for($start = strtotime($sdate); $start <= strtotime($edate);$start += 3600*24){
					$date=date ( "Y-m-d", $start);
					for($i=1;$i<=3;$i++){
						$temp=$this->product_model->count_by_school_date_type($user['school'],$date,$i);//学校某天某餐是否有商品
						if(empty($temp)){
							continue;
						}
						$temp2=$this->orderdetail_model->count_by_order_date_type($orderid,$date,$i);
						if(!empty($temp2)){
							continue;
						}
						$orderdetail=array (
							'orderid' => $orderid,
							'productid' =>  $product['id'],
							'price' => $product['price'],
							'amount' => 1,
							'date' => $date,
							'type' => $i,
							'defaults' => 1
					    );
						$this->orderdetail_model->create ( $orderdetail );
					}
				}
			}
			$newuser = array (
				'order_state' => 1
			);
			$this->user_model->update ( $user['id'], $newuser );
			$this->db->trans_commit();
			return_json ( TRUE, $orderid, '订单创建成功！' );
		}else{
			return_json ( FALSE, '', '订单创建失败！' );
		}
	}
	/*
	 * 取消订单
	 */
	public function cancel() {
		$userid = $this->session->userdata ( 'id' );
		if(empty($userid)){
			return_json ( FALSE, '', '请重新登录后再操作！' );
		}
		$this->load->model ( 'user_model' );
		$user = $this->user_model->load($userid);
		$orderid = $this->input->post ( 'orderid' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'product_model' );
		$order= $this->order_model->load ( $orderid );
		if($order['state']==0){//只有未确认时才可以取消订单
			$neworder= array (
				'del' => 1
			);
			if($this->order_model->update ( $orderid,$neworder )){
				$details=$this->orderdetail_model->find_by_order($orderid);
				foreach($details as $item){
					$this->product_model->updateStock2($user['school'],$item['date'],$item['productid'],$item['type'],$item['amount']);
				}
				$newuser= array (
					'order_state' => 0
				);
				$this->user_model->update ( $userid,$newuser );//将用户恢复为可订餐的状态
				return_json ( TRUE, '', '取消订单成功！' );
			}else{
				return_json ( FALSE, '', '取消订单失败！' );
			}
		}else{
			return_json ( FALSE, '', '该订单已确认，不能取消！' );
		}
	}
	/*
	 * 返回用户的订单
	 */
	public function myorder() {
		$state = $this->uri->segment ( 3 );
		if(!isset($state)){//没有传值时默认为-1
			$state=-1;
		}
		$userid = $this->session->userdata ( 'id' );
		$this->load->model ( 'order_model' );
		$data ['orders'] = $this->order_model->find_by_user_state ( $userid,$state );
		$data ['state'] = $state;
		$this->load->view ( 'order/myorder', $data );
	}
	/*
	 * 返回订单详情信息
	 */
	public function detail() {
		$id = $this->uri->segment ( 4 );
		$this->load->model ( 'order_model' );
		$data ['order']= $this->order_model->load ( $id );
		$this->load->model ( 'orderdetail_model' );
		$data ['orderdetails'] = $this->orderdetail_model->find_by_order ( $id );
		$this->load->view ( 'order/orderdetail', $data );
	}
	/*
	 * 跳转到商品评价页面
	 */
	public function comment() {
		$id = $this->uri->segment ( 4 );
		$this->load->model ( 'product_model' );
		$data ['product'] = $this->product_model->load ( $id );
		$this->load->view ( 'order/comment', $data );
	}
	/*
	 * 保存商品评价信息
	 */
	public function savecomment() {
		$userid = $this->session->userdata ( 'id' );
		$productid = $this->input->post ( 'productid' );
		$score = $this->input->post ( 'score' );
		$content = $this->input->post ( 'content' );
		$this->load->model ( 'comment_model' );
		$comment = array (
			'userid' => $userid,
			'productid' => $productid,
			'score' => $score,
			'content' => $content,
			'date'=>date ( "Y-m-d H:i:s" ) 
		);
		$commentid=$this->comment_model->create ($comment);
		if(!empty($commentid)){
			return_json ( TRUE, '', '评价成功！' );
		}else{
			return_json ( FAlSE, '', '评价失败！' );
		}
	}
	/*
	 * 返回用户购物车内商品的总价格
	 */
	private function count_total_price($userid) {
		$this->load->model ( 'shoppingcart_model' );
		$carts = $this->shoppingcart_model->find_by_user ( $userid );
		$total=0;
		foreach($carts as $cart){
			$total+=$cart['price']*$cart['amount'];
		}
		return $total;
	}
	
	
	/*
	 * 跳转到支付页面(暂时没用)
	 */
	public function pay() {
		$id = $this->uri->segment ( 3 );
		$this->load->model ( 'order_model' );
		$order = $this->order_model->load ( $id );
		$data ['order'] =$order;
		$userid = $this->session->userdata ( 'id' );
		$this->load->model ( 'user_model' );
		$user = $this->user_model->load ( $userid );
		$data['user'] =$user;
		$this->load->view ( 'order/orderinfo', $data );
	}
	/*
	 * 余额支付处理(暂时没用)
	 */
	public function submitpay() {
		$orderid = $this->input->post ( 'orderid' );
		$code = $this->input->post ( 'code' );
		$scode=$this->session->userdata('scode');
		if($code==$scode){//防止重复提交表单
			return_json ( FALSE, '', '请勿重复提交！' );
		}else{
			$this->session->set_userdata ( 'scode',$code);
		
			$userid = $this->session->userdata ( 'id' );
			$this->load->model ( 'user_model' );
			$user = $this->user_model->load ( $userid );
			$this->load->model ( 'order_model' );
			$order = $this->order_model->load ( $orderid );
		
			$balance=$user['balance']-$order['total'];//默认余额支付
			if($balance<0){
				return_json ( FALSE, '', '余额不足！请及时充值！' );
			}
			$newuser= array (
				'balance' => $balance
			);
			$this->user_model->update ( $userid,$newuser );//更新用户账户余额
			$neworder= array (
				'state' => 1,
				'payment_mode'=> 1,
				'payment_time'=>date ( 'Y-m-d H:i:s', time () )
			);
			$this->order_model->update ( $orderid,$neworder );//更新订单信息
			return_json ( TRUE, '', '支付成功！' );
		}
	}
}